import cv2

img1 = cv2.imread('book.jpg', cv2.IMREAD_COLOR)
img2 = cv2.imread('book_cover.jpg', cv2.IMREAD_COLOR)
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

detector = cv2.xfeatures2d.SIFT_create()
#detector = cv2.ORB_create()
kp1, des1 = detector.detectAndCompute(gray1, None)
kp2, des2 = detector.detectAndCompute(gray2, None)
#matcher = cv2.FlannBasedMatcher()
matcher = cv2.BFMatcher()
# 匹配特征描述子
matches = matcher.knnMatch(des1, des2, k=2)
# 计算最近与次近距离的比值, 挑选小于阈值的匹配对
good_matches = []
for m1, m2 in matches:
    ratio = m1.distance / m2.distance
    if ratio < 0.7:
        good_matches.append(m1)
dst = cv2.drawMatches(img1, kp1, img2, kp2, good_matches, None)
cv2.imshow('Feature match', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()